package com.ruoyi.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.domain.SysConfig2;
import com.ruoyi.mapper.SysConfig2Mapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.net.NetUtil;

import java.net.InetAddress;



import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@RestController
@Api(tags = "机器狗")
@SaCheckLogin
@RequestMapping(value = "/ray/aibo/")
public class Aibo {

    @Autowired
    SysConfig2Mapper sysConfig2Mapper;

    private String pub = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzBZ5EGuhCWRR7VcVFtoWJXcewqe0CUr3CS8Csw5in46XS9q+v2jszeLkhLpt4ttzdDRqZMeEPsBNgbgpyeY7ohiAFemO3hZFnbHyykF9yykktb8RtAmE2VCz9AEFtRpgvQuMlDKSbT1AGRDuUVCVTeA/HO1gDMrjpOr7QD/3MbAE+h2dDSo4lesQYUu9aZlKKKsStlS5kDhUfXmOn7d6t0fjKwfsUGv0FLGzBzKWfTE4Rh2VoxYKdrv7+Liq+fTF5hcm3e7AW+mtRypX9FDgVWWul8Nob5l03asK5xOWUeoJf7IECk9NuS0R9C5dkpmysCyic3vAlwOEKsk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vpXMvhSYAdRCZjuwSOpeEmAJM8JN6MC07uzBy4Od+z+wKBgD2W2CH92BtjDvYsob2JebbEc0ajot10e9kAANnLz9N+rC0bgX+E19Ny3yv6PUAUrXls9iCArnjO87bIg5vD4VnkWPmDuLF++/Z2BvLbs7b+yoYwCEM+YMDKnC6L67+LqOOGmGY54v/ilolGzeRX6EbN0ghJJs5Tf0gqelj2GjMlAoGBAI5g94J39SD1qnr3jHDJdz5LcJu1lYXCSFLn+ObSGQ5jAmRqGgW9zAeaUqBbnAnoChRvx0uTHXHw+5+L8rvd6OtaO0fXCIY6uZIsx4ZfNA7eWxGO7WHakYrDdW7b7EUNVgLmsxaZvDHKOpZ8XaMJjEoy94OSiCVLuJ0djNHptVV/AoGBALjUiJ7XeqLlKuM9G10vTYCJti5AW0syr0y8DitKTo4hlfeeiXyY3hQhnzeXtQvJJkw3BMm6X3xNz8DR6Vf2m72Q5lJGAxHOiFoxow4pbahacMEkfX0i+MMDSv9q78J1GykSGUN7DjSvNGNgGW+t3pIVPiyJnEu7kpGFO4aGDg5K";

//    @SaIgnore
//    @ApiOperation("获取mac地址")
//    @GetMapping("get_mac")
//    public AjaxResult 获取本机mac地址() {
//
//        String mac = NetUtil.getLocalMacAddress();
//
//        return AjaxResult.success("",mac);
//    }

    @SaIgnore
    @ApiOperation("获取机器注册码")
    @GetMapping("get_reg_code")
    public AjaxResult 获取本机注册码() {






        try {
            String mac = NetUtil.getLocalMacAddress();
            String macAddress = NetUtil.getMacAddress(InetAddress.getLocalHost());
            System.out.println(macAddress);
            //获取本地ip和主机名
            InetAddress addr = InetAddress.getLocalHost();
            System.out.println("IP地址：" + addr.getHostAddress() + "，主机名：" + addr.getHostName());
            String name = addr.getHostName();


            Map<String,Object> map = new HashMap<>();
            map.put("mac",mac);
            map.put("name",name);
            map.put("time",new Date().getTime()/1000);
            String jsonStr = JSONUtil.toJsonStr(map);

            String code = 加密(jsonStr,this.pub);
//            System.out.println("code = " + code);
//            String res= 解密( code,this.pri);
//            System.out.println("解密 = " + res);


            return AjaxResult.success("",code);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }


    }


    @SaIgnore
    @ApiOperation("更新机器授权码")
    @GetMapping("update_code")
    public AjaxResult 更新本机授权码(String code) {


        String res = null;
        try {
            res= 解密( code,this.pri);
        } catch (Exception e) {
            return  AjaxResult.error("错误授权码",code);
        }

//        System.out.println("解密 = " + res);

        JSONObject json = JSONUtil.parseObj(res);
        String mac = NetUtil.getLocalMacAddress();
        if(mac.equals(json.get("mac").toString())){

        }else{
            return AjaxResult.error("这是 "+json.getStr("name")+" 的授权码");
        }

        // MD5加密
        String md5 = DigestUtil.md5Hex(mac);
        md5 = DigestUtil.md5Hex(md5);
        if(md5.equals(json.get("md5").toString()))
        {

            QueryWrapper qw = new QueryWrapper<>();
            qw.eq("config_key","ray.authorization_code");
            SysConfig2 sys = sysConfig2Mapper.selectOne(qw);
            sys.setConfigValue(code);
            sysConfig2Mapper.update(sys,qw);


            return AjaxResult.success("授权成功",json);
        }else{
            return  AjaxResult.error("错误授权码",md5);
        }


    }


    @SaIgnore
    @ApiOperation("本机是否已授权")
    @Description("本接口只是方便调试，实际没有该接口，该接口是厂家才有")
    @GetMapping("is_authorized")
    public AjaxResult 本机是否已授权() {
        boolean res = isEmpower();
        return AjaxResult.success(res?"成功授权":"未授权",res);
    }

    //是否已授权
    public boolean isEmpower(){
        //获取本机配置的授权码
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("config_key","ray.authorization_code");
        SysConfig2 sys = sysConfig2Mapper.selectOne(qw);
        String code = sys.getConfigValue();
        if(code.isEmpty()){
            return false;
        }
        String res = null;
        try {
            res= 解密( code,this.pri);
        } catch (Exception e) {
            return false;
        }


        System.out.println("解密 = " + res);

        JSONObject json = JSONUtil.parseObj(res);
        String mac = NetUtil.getLocalMacAddress();
        if(mac.equals(json.get("mac").toString())){

        }else{
            return false;
        }
        // MD5加密
        String md5 = DigestUtil.md5Hex(mac);
        md5 = DigestUtil.md5Hex(md5);
        if(md5.equals(json.get("md5").toString()))
        {
            return true;
        }
        return false;
    }


    @SaIgnore
    @ApiOperation("注册机")
    @Description("本接口只是方便调试，实际没有该接口，该接口是厂家才有")
    @GetMapping("get_code")
    public AjaxResult 注册机(String code) {




        String res = null;
        try {
            res= 解密( code,this.pri);
        } catch (Exception e) {
            return  AjaxResult.error("错误注册码");
        }

        if(res.isEmpty() || res==null || res.equals(""))
        {
            return  AjaxResult.error("错误注册码");
        }
        System.out.println("解密 = " + res);


        JSONObject json = JSONUtil.parseObj(res);
        String mac =json.get("mac").toString();
        // MD5加密
        String md5 = DigestUtil.md5Hex(mac);
        md5 = DigestUtil.md5Hex(md5);

        Map<String,Object> map = new HashMap<>();
        map.put("mac",mac);
        map.put("name",json.get("name").toString());
        map.put("md5",md5);
        map.put("time",new Date().getTime()/1000);
        String jsonStr = JSONUtil.toJsonStr(map);

        try{
            code = 加密(jsonStr,this.pub);
        }catch (Exception e) {
            return  AjaxResult.error("加密失敗"+e.getMessage());
        }


        return AjaxResult.success("授权码",code);
    }








    //获取密钥方法
    public static Map<String,String> getPairKey(){
        Map<String,String> map=new HashMap<>();
        RSA rsa = new RSA();
        map.put("public",rsa.getPublicKeyBase64());
        map.put("private",rsa.getPrivateKeyBase64());
        return map;
    }

    //解密方法--ciphertext：为密文，privateKey：为私钥
    public static String 解密(String ciphertext,String privateKey){
        RSA rsa = new RSA(privateKey, null);
        byte[] decode = Base64.getDecoder().decode(ciphertext);
        byte[] passwordBytes = rsa.decrypt(decode, KeyType.PrivateKey);
        return StrUtil.str(passwordBytes, CharsetUtil.CHARSET_UTF_8);
    }

    //加密方法--text：为需要加密的字符串，publicKey：为公钥
    public static String 加密(String text,String publicKey) throws UnsupportedEncodingException {
        RSA rsa = new RSA(null, publicKey);
        byte[] encrypt = rsa.encrypt(StrUtil.bytes(text, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
        String encode = Base64.getEncoder().encodeToString(encrypt);
        return encode;
    }




}